// 俄罗斯方块游戏逻辑

// 游戏常量
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 30;
const COLORS = [
    'cyan', 'blue', 'orange', 'yellow', 'green', 'purple', 'red'
];

// 方块形状
const SHAPES = [
    [],
    [[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]], // I
    [[1, 0, 0], [1, 1, 1], [0, 0, 0]], // J
    [[0, 0, 1], [1, 1, 1], [0, 0, 0]], // L
    [[1, 1], [1, 1]], // O
    [[0, 1, 1], [1, 1, 0], [0, 0, 0]], // S
    [[0, 1, 0], [1, 1, 1], [0, 0, 0]], // T
    [[1, 1, 0], [0, 1, 1], [0, 0, 0]]  // Z
];

// 游戏变量
let canvas, ctx;
let board = [];
let score = 0;
let level = 1;
let lines = 0;
let gameOver = false;
let paused = false;
let currentPiece, nextPiece;
let dropCounter = 0;
let dropInterval = 1000;
let lastTime = 0;

// DOM元素
const gameBoard = document.getElementById('gameBoard');
const nextPieceBoard = document.getElementById('nextPieceBoard');
const scoreElement = document.getElementById('score');
const levelElement = document.getElementById('level');
const linesElement = document.getElementById('lines');
const startBtn = document.getElementById('startBtn');
const restartBtn = document.getElementById('restartBtn');

// 移动端控制按钮
const leftBtn = document.getElementById('leftBtn');
const rightBtn = document.getElementById('rightBtn');
const downBtn = document.getElementById('downBtn');
const rotateBtn = document.getElementById('rotateBtn');
const dropBtn = document.getElementById('dropBtn');

// 初始化游戏
function init() {
    createBoard();
    resetGame();
    addEventListeners();
    drawBoard();
    drawNextPieceBoard();
    
    // 开始游戏循环
    requestAnimationFrame(update);
}

// 创建游戏板
function createBoard() {
    // 清空现有的游戏板
    gameBoard.innerHTML = '';
    nextPieceBoard.innerHTML = '';
    
    // 创建主游戏板
    for (let y = 0; y < ROWS; y++) {
        board[y] = [];
        for (let x = 0; x < COLS; x++) {
            board[y][x] = 0;
            const cell = document.createElement('div');
            cell.className = 'cell';
            cell.id = `cell-${y}-${x}`;
            gameBoard.appendChild(cell);
        }
    }
    
    // 创建下一个方块预览板
    for (let y = 0; y < 4; y++) {
        for (let x = 0; x < 4; x++) {
            const cell = document.createElement('div');
            cell.className = 'next-piece-cell';
            cell.id = `next-${y}-${x}`;
            nextPieceBoard.appendChild(cell);
        }
    }
}

// 重置游戏
function resetGame() {
    // 清空游戏板
    for (let y = 0; y < ROWS; y++) {
        for (let x = 0; x < COLS; x++) {
            board[y][x] = 0;
        }
    }
    
    // 重置游戏状态
    score = 0;
    level = 1;
    lines = 0;
    gameOver = false;
    paused = false;
    dropInterval = 1000;
    
    // 更新显示
    updateScore();
    
    // 创建新的方块
    nextPiece = createPiece();
    createNewPiece();
}

// 创建新方块
function createPiece() {
    const typeId = Math.floor(Math.random() * 7) + 1;
    return {
        typeId: typeId,
        shape: SHAPES[typeId],
        x: Math.floor(COLS / 2) - 1,
        y: 0
    };
}

// 创建新方块并检查游戏结束
function createNewPiece() {
    currentPiece = nextPiece;
    nextPiece = createPiece();
    drawNextPiece();
    
    // 检查游戏是否结束
    if (checkCollision()) {
        gameOver = true;
        alert('游戏结束! 您的得分: ' + score);
    }
}

// 绘制下一个方块预览
function drawNextPiece() {
    // 清空预览板
    for (let y = 0; y < 4; y++) {
        for (let x = 0; x < 4; x++) {
            const cell = document.getElementById(`next-${y}-${x}`);
            cell.className = 'next-piece-cell';
        }
    }
    
    // 绘制下一个方块
    const shape = nextPiece.shape;
    for (let y = 0; y < shape.length; y++) {
        for (let x = 0; x < shape[y].length; x++) {
            if (shape[y][x]) {
                const cell = document.getElementById(`next-${y}-${x}`);
                cell.classList.add('next-piece-cell', 'filled', getPieceClass(nextPiece.typeId));
            }
        }
    }
}

// 绘制游戏板
function drawBoard() {
    for (let y = 0; y < ROWS; y++) {
        for (let x = 0; x < COLS; x++) {
            const cell = document.getElementById(`cell-${y}-${x}`);
            cell.className = 'cell';
            if (board[y][x]) {
                cell.classList.add('filled', getColorClass(board[y][x]));
            }
        }
    }
    
    // 绘制当前方块
    if (currentPiece) {
        const shape = currentPiece.shape;
        for (let y = 0; y < shape.length; y++) {
            for (let x = 0; x < shape[y].length; x++) {
                if (shape[y][x]) {
                    const boardY = currentPiece.y + y;
                    const boardX = currentPiece.x + x;
                    if (boardY >= 0) {
                        const cell = document.getElementById(`cell-${boardY}-${boardX}`);
                        if (cell) {
                            cell.classList.add('filled', getPieceClass(currentPiece.typeId));
                        }
                    }
                }
            }
        }
    }
}

// 绘制下一个方块预览板
function drawNextPieceBoard() {
    // 这个函数已经在drawNextPiece中处理了
}

// 获取方块颜色类名
function getPieceClass(typeId) {
    const classes = ['I', 'J', 'L', 'O', 'S', 'T', 'Z'];
    return classes[typeId - 1] || '';
}

// 获取颜色类名
function getColorClass(typeId) {
    const classes = ['I', 'J', 'L', 'O', 'S', 'T', 'Z'];
    return classes[typeId - 1] || '';
}

// 移动方块
function movePiece(dx, dy) {
    if (gameOver || paused) return;
    
    currentPiece.x += dx;
    currentPiece.y += dy;
    
    if (checkCollision()) {
        currentPiece.x -= dx;
        currentPiece.y -= dy;
        
        // 如果向下移动发生碰撞，则锁定方块
        if (dy > 0) {
            lockPiece();
            clearLines();
            createNewPiece();
        }
        
        return false;
    }
    
    return true;
}

// 旋转方块
function rotatePiece() {
    if (gameOver || paused) return;
    
    const originalShape = currentPiece.shape;
    // 创建旋转后的新形状
    const newShape = [];
    for (let x = 0; x < originalShape[0].length; x++) {
        const row = [];
        for (let y = originalShape.length - 1; y >= 0; y--) {
            row.push(originalShape[y][x]);
        }
        newShape.push(row);
    }
    
    const originalShapeBackup = currentPiece.shape;
    currentPiece.shape = newShape;
    
    // 检查旋转后是否发生碰撞
    if (checkCollision()) {
        // 如果发生碰撞，恢复原始形状
        currentPiece.shape = originalShapeBackup;
    }
}

// 检查碰撞
function checkCollision() {
    const shape = currentPiece.shape;
    for (let y = 0; y < shape.length; y++) {
        for (let x = 0; x < shape[y].length; x++) {
            if (shape[y][x]) {
                const boardY = currentPiece.y + y;
                const boardX = currentPiece.x + x;
                
                // 检查边界
                if (boardX < 0 || boardX >= COLS || boardY >= ROWS) {
                    return true;
                }
                
                // 检查是否与已放置的方块碰撞
                if (boardY >= 0 && board[boardY][boardX]) {
                    return true;
                }
            }
        }
    }
    
    return false;
}

// 锁定方块
function lockPiece() {
    const shape = currentPiece.shape;
    for (let y = 0; y < shape.length; y++) {
        for (let x = 0; x < shape[y].length; x++) {
            if (shape[y][x]) {
                const boardY = currentPiece.y + y;
                const boardX = currentPiece.x + x;
                if (boardY >= 0) {
                    board[boardY][boardX] = currentPiece.typeId;
                }
            }
        }
    }
}

// 清除满行
function clearLines() {
    let linesCleared = 0;
    
    for (let y = ROWS - 1; y >= 0; y--) {
        let isLineFull = true;
        for (let x = 0; x < COLS; x++) {
            if (!board[y][x]) {
                isLineFull = false;
                break;
            }
        }
        
        if (isLineFull) {
            // 移除这一行
            for (let yy = y; yy > 0; yy--) {
                for (let x = 0; x < COLS; x++) {
                    board[yy][x] = board[yy-1][x];
                }
            }
            
            // 清空顶部行
            for (let x = 0; x < COLS; x++) {
                board[0][x] = 0;
            }
            
            linesCleared++;
            y++; // 重新检查当前行
        }
    }
    
    if (linesCleared > 0) {
        // 更新得分
        const points = [0, 100, 300, 500, 800]; // 不同行数的得分
        score += points[linesCleared] * level;
        lines += linesCleared;
        level = Math.floor(lines / 10) + 1;
        
        // 增加难度
        dropInterval = Math.max(100, 1000 - (level - 1) * 100);
        
        updateScore();
    }
}

// 更新得分显示
function updateScore() {
    scoreElement.textContent = score;
    levelElement.textContent = level;
    linesElement.textContent = lines;
}

// 更新游戏状态
function update(time = 0) {
    const deltaTime = time - lastTime;
    lastTime = time;
    
    if (!paused && !gameOver) {
        dropCounter += deltaTime;
        if (dropCounter > dropInterval) {
            movePiece(0, 1);
            dropCounter = 0;
        }
    }
    
    drawBoard();
    requestAnimationFrame(update);
}

// 添加事件监听器
function addEventListeners() {
    // 键盘控制
    document.addEventListener('keydown', event => {
        if (gameOver) return;
        
        switch (event.keyCode) {
            case 37: // 左箭头
                movePiece(-1, 0);
                break;
            case 39: // 右箭头
                movePiece(1, 0);
                break;
            case 40: // 下箭头
                movePiece(0, 1);
                break;
            case 38: // 上箭头
                rotatePiece();
                break;
            case 32: // 空格
                // 硬降
                while (movePiece(0, 1)) {}
                break;
        }
    });
    
    // 开始/暂停按钮
    startBtn.addEventListener('click', () => {
        if (gameOver) {
            resetGame();
        } else {
            paused = !paused;
            startBtn.textContent = paused ? '继续' : '暂停';
        }
    });
    
    // 移动端控制按钮
    if (leftBtn) {
        leftBtn.addEventListener('touchstart', function(e) {
            e.preventDefault();
            movePiece(-1, 0);
        });
        
        leftBtn.addEventListener('mousedown', function() {
            movePiece(-1, 0);
        });
    }
    
    if (rightBtn) {
        rightBtn.addEventListener('touchstart', function(e) {
            e.preventDefault();
            movePiece(1, 0);
        });
        
        rightBtn.addEventListener('mousedown', function() {
            movePiece(1, 0);
        });
    }
    
    if (downBtn) {
        downBtn.addEventListener('touchstart', function(e) {
            e.preventDefault();
            movePiece(0, 1);
        });
        
        downBtn.addEventListener('mousedown', function() {
            movePiece(0, 1);
        });
    }
    
    if (rotateBtn) {
        rotateBtn.addEventListener('touchstart', function(e) {
            e.preventDefault();
            rotatePiece();
        });
        
        rotateBtn.addEventListener('mousedown', function() {
            rotatePiece();
        });
    }
    
    if (dropBtn) {
        dropBtn.addEventListener('touchstart', function(e) {
            e.preventDefault();
            // 硬降
            while (movePiece(0, 1)) {}
        });
        
        dropBtn.addEventListener('mousedown', function() {
            // 硬降
            while (movePiece(0, 1)) {}
        });
    }
    
    // 防止双击缩放
    let lastTouchEnd = 0;
    document.addEventListener('touchend', function (event) {
        const now = (new Date()).getTime();
        if (now - lastTouchEnd <= 300) {
            event.preventDefault();
        }
        lastTouchEnd = now;
    }, false);
    
    // 防止按钮的默认触摸行为
    const buttons = document.querySelectorAll('.mobile-btn');
    buttons.forEach(button => {
        button.addEventListener('touchstart', function(e) {
            e.preventDefault();
        });
    });
}

// 重开按钮事件
restartBtn.addEventListener('click', function() {
    // 重置游戏状态
    board = Array.from(Array(ROWS), () => Array(COLS).fill(0));
    score = 0;
    level = 1;
    lines = 0;
    gameOver = false;
    paused = false;
    dropInterval = 1000;
    
    // 重新创建游戏板
    createBoard();
    
    // 生成新方块
    currentPiece = createPiece();
    nextPiece = createPiece();
    
    // 更新显示
    updateScore();
    drawBoard();
    drawNextPiece();
    
    // 如果游戏暂停，恢复游戏
    if (paused) {
        paused = false;
        startBtn.textContent = '暂停';
    }
});

// 启动游戏
init();